package com.bbcare.treat.plat.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bbcare.comm.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.treat.plat.service.IPatientArchService;
import com.bbcare.treat.plat.service.IPatientTreatService;

/**
 * @name: 患者门诊诊疗相关处理类
 * @author: DemonLee
 * @createTime: 2018.8.15
 * @description: 患者门诊诊疗相关操作
 * @modify:
 *
 */
@Controller
@RequestMapping("/service/treat")
public class PatientTreatController {
    private final Log logger = LogFactory.getLog(PatientTreatController.class);

    @Autowired
    private IPatientTreatService patientTreatService;

    @Autowired
    private IFollowQueueService followQueueSerivce;

    @Autowired
    private IPatientArchService patientArchService;

    // 根据队列id查询当前专病的任务内容
    @ResponseBody
    @RequestMapping("/listSpecialDiseaseTask")
    public ResultModel<Map<String, Object>> listSpecialDiseaseTask(@RequestBody String arg) throws Exception {
        logger.warn("in listSpecialDiseaseTask----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，无data节点！"));
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        String queueId = jsonData.getString("followQueueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，队列id为空！"));
        }
        Integer schemeBusiType = jsonData.getInteger("schemeBusiType");
        if (null == schemeBusiType) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，方案业务类型为空！"));
        }

        retMap = patientTreatService.listSpecialTask(jsonData);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 查询队列建档问卷内容
    @ResponseBody
    @RequestMapping("/qryQueueArchiveContent")
    public ResultModel<Map<String, Object>> getQueueArchiveContent(@RequestBody String arg) throws Exception {
        logger.warn("in getQueueArchiveContent----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，无data节点！"));
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        String queueId = jsonData.getString("followQueueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，队列id为空！"));
        }

        retMap = patientTreatService.getQueueArchiveContent(jsonData);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 新版患者建档
    @ResponseBody
    @RequestMapping("/patientAddNew")
    public ResultModel<Map<String, Object>> savePatientArchiveInfo(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in savePatientArchiveInfo----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，无data节点！"));
        }
        String currTime = jsonData.getString("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(currTime)) {
            currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

        // 参数校验后续补充
        String queueId = jsonData.getString("followQueueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，未传入队列id或值为空！"));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> chkMapIn = new HashMap<String, Object>();
        boolean isVerify = true;
        map.put("id", queueId);
        chkMapIn.put("queueId", queueId);
        FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
        if (null == queue) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
        }
        String queueUserType = queue.getQueueUsertype();

        Map<String, Object> servParamMap = jsonData;

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("deptId");

        String opCode = jsonData.getString("opCode");
        String opType = jsonData.getString("opType");
        if (StringUtils.isBlank(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，操作编码为空！"));
        }
        if (StringUtils.isBlank(opType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，操作类型为空！"));
        }
        if (StringUtils.isBlank(jsonData.getString("opNote"))) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，操作备注为空！"));
        }
        String userType = jsonData.getString("userType");
        if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            // 孕产妇（母亲），暂时写死，回头完善
            userType = "2";
        } else if (StringUtils.isBlank(userType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者类型为空！"));
        }

        // 入参中没有，从问卷答案中获取
        Map<String, Object> quesMap = (JSONObject) jsonData.getJSONObject("questiones");
        String phoneNum = jsonData.getString("phoneNum");
        if (StringUtils.isBlank(phoneNum) && MapUtils.isNotEmpty(quesMap)) {
            phoneNum = (String) quesMap.get(Constants.QUESTION_ID_FOR_PHONENO);
        }
        if (StringUtils.isBlank(phoneNum)) {
            phoneNum = "";
            chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PHONENO);
            isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
            if (isVerify) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号码不能为空！"));
            }
        }
        phoneNum = phoneNum.trim();

        String patientName = jsonData.getString("patientName");
        if (StringUtils.isBlank(patientName) && MapUtils.isNotEmpty(quesMap)) {
            patientName = (String) quesMap.get(Constants.QUESTION_ID_FOR_PATIENTNAME);
        }
        if (StringUtils.isBlank(patientName)) {
            patientName = "";
            chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PATIENTNAME);
            isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
            if (isVerify) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者姓名不能为空！"));
            }
        }
        patientName = patientName.trim();

        String gender = jsonData.getString("gender");
        if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            // 孕产妇（母亲）
            gender = Constants.GENDER_FOR_FEMALE;
        } else if (StringUtils.isBlank(gender) && MapUtils.isNotEmpty(quesMap)) {
            gender = (String) quesMap.get(Constants.QUESTION_ID_FOR_GENDER);
        }
        if (StringUtils.isBlank(gender)) {
            gender = "";
            chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_GENDER);
            isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
            if (isVerify) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "性别不能为空！"));
            }
        }
        gender = gender.trim();
        // 转换性别
        if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender)) {
            gender = Constants.GENDER_FOR_MALE;
        } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender)) {
            gender = Constants.GENDER_FOR_FEMALE;
        } else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
            gender = Constants.GENDER_FOR_MALE;
        }

        String birthday = jsonData.getString("birthday");
        if (StringUtils.isBlank(birthday) && MapUtils.isNotEmpty(quesMap)) {
            birthday = (String) quesMap.get(Constants.QUESTION_ID_FOR_BIRTHDAY);
        }
        if (StringUtils.isBlank(birthday) && !Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            birthday = null;
            chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_BIRTHDAY);
            isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
            if (isVerify) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "出生日期不能为空！"));
            }
        }

        // 预产期
        String expectedDay = jsonData.getString("expectedDay");
        if (StringUtils.isBlank(expectedDay) && MapUtils.isNotEmpty(quesMap)) {
            expectedDay = (String) quesMap.get(Constants.QUESTION_ID_FOR_EXPECTEDDAY);
        }
        if (StringUtils.isEmpty(expectedDay)) {
            expectedDay = null;
        }

        // 出生胎龄(孕周)
        int pregnancyDay = 0;
        // 直接从入参中获取
        if (null != jsonData.getInteger("pregnancyWeek")) {
            pregnancyDay = jsonData.getIntValue("pregnancyWeek");
        }
        // 再考虑从问卷中获取，问卷存储格式：[39,5]
        if (pregnancyDay <= 0 && !MapUtils.isEmpty(quesMap)) {
            String preStr = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCYDAY);
            if (!StringUtils.isBlank(preStr)) {
                String preArr[] = preStr.split(Constants.COMMA_SPLIT_STR);
                if (null != preArr && 2 == preArr.length) {
                    String preWeekStr = preArr[0].substring(1);
                    String preDayStr = preArr[1].substring(0, preArr[1].length() - 1);
                    int preWeek = Integer.parseInt(preWeekStr);
                    int preDay = Integer.parseInt(preDayStr);
                    pregnancyDay = preWeek * Constants.PREGNANCY_CALC_UNIT_WEEK + preDay;
                }
            }
        }
        // 最后根据根据生日和预产期计算
        if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            // 孕产妇（母亲）
            // 初检孕周
            String firstChkPregWeek = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCY_FIRST_WEEK);
            if (StringUtils.isBlank(firstChkPregWeek)) {
                // 不在这里校验，在实例化随访任务时校验
            } else {
                servParamMap.put("firstChkPregWeek", Integer.parseInt(firstChkPregWeek));
            }
            // 末次月经日期
            String lastMenstruationDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_LAST_MENSTRUATION_DATE);
            if (StringUtils.isBlank(lastMenstruationDate)) {
                // 不在这里校验，在实例化随访任务时校验
            } else {
                servParamMap.put("lastMenstruationDate", lastMenstruationDate);
            }
            // 分娩日期
            servParamMap.put("deliveryDate", quesMap.get(Constants.QUESTION_ID_FOR_LAST_DELIVERY_DATE));
        } else if (pregnancyDay <= 0 && !StringUtils.isBlank(expectedDay)) {
            pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
        }

        // 孕周未填，默认280
        if (pregnancyDay <= 0) {
            pregnancyDay = Constants.PATIENT_NORMAL_PREGNANT_DAY;
        }
        // 预产期未填，默认与出生日期一致
        if (StringUtils.isBlank(expectedDay)) {
            expectedDay = birthday;
        }
        // 来源渠道
        String sourceType = jsonData.getString("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            // 默认web端门诊渠道
            sourceType = Constants.PATIENT_SOURCE_TYPE_DOOR;
        }

        Patient pt = new Patient();
        pt.setPregnancyDay(pregnancyDay);
        pt.setUserName(patientName);
        pt.setPhoneNo(phoneNum);
        pt.setFirstName(patientName.substring(0, 1));
        pt.setCreateTime(currTime);
        pt.setUpdateTime(currTime);
        pt.setCreateAuthor(author);
        pt.setBirthday(birthday);
        pt.setExpectedDay(expectedDay);
        pt.setGender(gender);
        pt.setUserType(userType);
        pt.setSourceType(sourceType);

        servParamMap.put("patient", pt);
        servParamMap.put("authorName", authorName);
        servParamMap.put("deptId", deptId);
        servParamMap.put("queueId", queueId);
        servParamMap.put("updateTime", currTime);
        servParamMap.put("authorId", author);
        servParamMap.put("updateAccept", updateAccept);
        servParamMap.put("tenantId", tenantId);
        servParamMap.put("opCode", opCode);
        servParamMap.put("opNote", jsonData.getString("opNote"));
        servParamMap.put("opType", opType);
        servParamMap.put("contentData", jsonData.getJSONObject("questiones"));

        List<Map<String, Object>> schemeList = ToolUtils.typeCast(jsonData.getJSONArray("schemeList"));
        Map<String, Object> userMap = new HashMap<String, Object>();
        int shsize = schemeList.size();
        int sh = 0;
        Map<String, Object> schemeMap = new HashMap<String, Object>();
        Integer schemeBusiType = 0;
        String schemeId = "";
        // 如果有数据，则校验
        for (sh = 0; sh < shsize; sh++) {
            schemeMap = schemeList.get(sh);
            schemeBusiType = (Integer) schemeMap.get("schemeBusiType");
            if (null == schemeBusiType) {
                throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，方案业务类型不能为空！");
            }
            schemeId = (String) schemeMap.get("schemeId");
            if (StringUtils.isBlank(schemeId)) {
                throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，方案id不能为空！");
            }
        }
        userMap = patientTreatService.savePatientArchives(servParamMap);

        return new ResultModel<Map<String, Object>>(userMap);
    }

    // 患者建档内容更新
    @ResponseBody
    @RequestMapping("/modifyPatientArchives")
    public ResultModel<Map<String, Object>> modifyPatientArchives(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in modifyPatientArchives----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，无data节点！"));
        }
        Map<String, Object> jsonTask = jsonData.getJSONObject("taskInfo");
        if (MapUtils.isEmpty(jsonTask)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，无task节点！"));
        }
        Map<String, Object> jsonOpInfo = jsonData.getJSONObject("oprInfo");
        if (MapUtils.isEmpty(jsonOpInfo)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，无oprInfo节点！"));
        }
        String opCode = (String) jsonOpInfo.get("opCode");
        if (StringUtils.isBlank(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，无操作编码节点！"));
        }
        String opNote = (String) jsonOpInfo.get("opNote");
        if (StringUtils.isBlank(opNote)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，操作备注为空！"));
        }
        String opType = (String) jsonOpInfo.get("opType");
        if (StringUtils.isBlank(opType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，操作类型为空！"));
        }
        String queueId = (String) jsonOpInfo.get("followQueueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，无队列id节点！"));
        }
        String ptSchemeId = (String) jsonOpInfo.get("ptSchemeId");
        if (StringUtils.isBlank(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参校验失败，未传入患者队列实例id或值为空！"));
        }
        String userId = (String) jsonOpInfo.get("patientId");
        if (StringUtils.isBlank(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者id未传或值为空！"));
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("deptId");// 科室id,修改手机号同步app使用
        jsonOpInfo.put("authorName", authorName);
        jsonOpInfo.put("deptId", deptId);
        jsonOpInfo.put("authorId", author);
        jsonOpInfo.put("tenantId", tenantId);

        String taskId = (String) jsonTask.get("ptTaskId");
        if (StringUtils.isBlank(taskId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参校验失败，未传入患者任务id或值为空！"));
        }
        String updateAuname = (String) jsonTask.get("updateAuname");
        if (StringUtils.isBlank(updateAuname)) {
            updateAuname = authorName;
        }
        jsonTask.put("updateAuname", updateAuname);

        String contentData = jsonData.getString("questions");
        if (StringUtils.isBlank(contentData)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参校验失败，未传入任务内容报文或值为空！"));
        }

        String opTime = (String) jsonOpInfo.get("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(opTime)) {
            opTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        jsonOpInfo.put("updateTime", opTime);
        jsonOpInfo.put("updateAccept", updateAccept);

        Map<String, Object> retMap = patientTreatService.modifyPtArchivesData(jsonData);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 门诊记录查询redis版接口（如今日门诊记录等）
    @ResponseBody
    @RequestMapping("/patientOperateListRedis")
    public ResultModel<Map<String, Object>> listOutPatientOperateRedis(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
        logger.warn("in listOutPatientOperateRedis----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，无data节点！"));
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        // flag: 0 今日门诊记录
        String flag = jsonData.getString("flag");
        if (StringUtils.isBlank(flag)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，flag节点为空！"));
        }
        // qryType: 0 按登录账号查询; 1 按队列查询; 2 按租户查询...
        Integer qryType = jsonData.getInteger("qryType");
        if (null == qryType) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，查询类型为空！"));
        }
        if (0 != qryType && 1 != qryType && 2 != qryType) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，查询类型暂不支持！"));
        }

        paramMap.put("qryType", qryType);
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);
        // 查询指定条数，redis与mysql有区别
        paramMap.put("redisStart", (page - 1) * rows);
        paramMap.put("redisEnd", page * rows - 1);
        String queueId = jsonData.getString("queueId");
        if (1 == qryType && StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，队列id为空！"));
        }
        paramMap.put("queueId", queueId);

        // 方案业务类型，0:科研随访方案；1:门诊诊疗方案；2:待扩展...可不传，不传的情况下默认为0（为兼容老的随访系统）
        Integer schemeBusiType = jsonData.getInteger("schemeBusiType");
        if (null == schemeBusiType) {
            schemeBusiType = Constants.SCHEME_BUSI_TYPE_0;
        }
        paramMap.put("schemeBusiType", schemeBusiType);

        Map<String, Object> retMap = patientTreatService.listPtOutPatientOperByRedis(paramMap);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    /**
     * @description：上传文件接口
     * @author:DemonLee
     * @date: 2017.9.4
     */
    @ResponseBody
    @RequestMapping("/uploadMultiFile")
    public Object uploadMultiFile(HttpServletResponse response, HttpServletRequest request) throws Exception {
        logger.info("---in uploadMultiFile---");
        List<String> filepathList = new ArrayList<String>();

        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            if (iter.hasNext()) {
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next());
                    if (!file.isEmpty()) {
                        String filepath = OSSClientUtil.uploadPicture(file,
                                PropertiesUtils.getProperty("treatFilePath"));// 保存图片
                        filepathList.add(filepath);
                    }
                }
            } else {
                throw new AppException(ErrorCode.FOLLOW_EXCEPTION_TYPE_UPLOAD_FILE_MPTY, "图片上传失败，上传文件为空");
            }
        }

        logger.info("out uploadMultiFile==filepathList==" + filepathList.toString());

        return new ResultModel<Object>(filepathList);
    }

    //用户诊疗信息
    @ResponseBody
    @RequestMapping("/import")
    public ResultModel<Object> EyesImport(HttpServletResponse response, HttpServletRequest request)
            throws Exception {
    	logger.info("in EyesImport ");
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");//登陆用户id
        String tenantId = (String) sessionMap.get("tenantId");//租户科室id

		if (multipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next());
                    if(!file.isEmpty()){
                    	String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1).toLowerCase();
                    	String fileNme =  file.getOriginalFilename();
                    	if(!"csv".equals(suffix)&& !"xlsx".equals(suffix) && !"xls".equals(suffix) && "xlsm".equals(suffix)){
                    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_FILE_TYPE_INCORRECT,"文件格式不对");
                        }

                    	if(ToolUtils.isExcel2003(file.getOriginalFilename())){
                    		HSSFWorkbook workbook=new HSSFWorkbook(file.getInputStream());
                    		patientTreatService.EyesImport(workbook,sessionMap,fileNme);
                    	}else if(ToolUtils.isExcel2007(file.getOriginalFilename())){
                    		XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
                    		patientTreatService.EyesImport(workbook,sessionMap,fileNme);
                    	}

                    	//写入文件保存
                    	String DateTime = DateUtil.getSysDate4Day();
                    	String fileNameSub = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
                		String fileName = fileNameSub + DateTime + "."+suffix;// 文件名
                		String parth = System.getProperty("user.dir");
                		String wholePath = parth + "\\" + "EysDowload";
                		logger.info("wholePath : "+wholePath);
                		File fileDir = new File(wholePath);
                		if (!fileDir.exists()) {
                			// 创建文件夹
                			fileDir.mkdirs();
                		}
                		File fout = new File(wholePath + "/" + fileName);
                		file.transferTo(fout);
                		/**写入文件结束***/

                    }
             }
        }

        Map<String,Object> requestParam = new  HashMap<String,Object>();
        requestParam.put("tenantId",tenantId);
        requestParam.put("authorId",authorId);
        Map<String, Object> rspMap = null;
        return new ResultModel<Object>(rspMap);
    }

}
